# -*- coding: utf-8 -*-
"""
Created on Tue Apr 30 11:20:56 2013

@author: Maxim
"""
import propeller
import dbTools
from numpy import array, linspace

def analyze_prop(name,rho,N,Jrange,betaRange):
    prop = propeller.load(name)
    d = prop.diameter
    n = N/60.0 #rps
    Vrange = Jrange*n*d
    J    = list()
    CP   = list()
    CT   = list()
    effy = list()
    for beta in betaRange:
        print '{0:10} beta:{1:.2f}'.format(name,beta)
        data = prop.analyze_at_velocity_range(beta,Vrange,N,rho)
        J.append(data[2])
        CP.append(data[4])
        CT.append(data[3])
        effy.append(data[5])
    return J,CP,CT,effy

def write_xls_data(dbPath,name,J,CP,CT,effy,betaRange):
    db = dbTools.loadDB(dbPath,mode='w')
    newSheet = db.add_sheet(name)
    sh = dbTools.writeDB(newSheet)
    for i,beta in enumerate(betaRange):
        sh.writeRow('beta:',float(beta))
        sh.writeRow('J',['effy','CP','CT'])
        for j in range(len(J[i])):
            nyu = effy[i][j]
            cp = CP[i][j]
            ct = CT[i][j]
            if nyu!=None and cp!=None and ct!=None:
                line = [J[i][j], nyu, cp, ct]
                sh.writeRow('',line)
        sh._prevRow +=1
    db.save_db()

def plot_data(J,CP,CT,effy,betaRange):
    import matplotlib.pyplot as plt
    fig = plt.figure(1)
    ax1 = fig.add_subplot(211)
    ax2 = fig.add_subplot(212)
    ax1.hold(True)
    ax2.grid(True)
    ax1.grid(True)
    for i,beta in enumerate(betaRange):
        ax1.plot(J[i],CP[i],'b-')
        ax2.plot(J[i],effy[i],'r-')
    plt.show()
def main_prop_data_generation():
    propellers = ['neuform','NACA5868','elprop3-1']
    Jrange     = linspace(0.05,1.5,50)
    #betaRange  = array([15.0,20.0,25.0,30.0,35.0])
    betaRange = array([10.0,20.0,25.0,30.0])
    N          = 1200.0 #rpm
    rho        = 1.2255
    dbName = r'D:\light aircraft\V05\propeller analysis\adsp_input_propeller.xls'
    for name in propellers:
        J,CP,CT,effy = analyze_prop(name,rho,N,Jrange,betaRange)
        #write_xls_data(dbName,name,J,CP,CT,effy,betaRange)
        plot_data(J,CP,CT,effy,betaRange)

if __name__=="__main__":
    main_prop_data_generation()